<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addInfo">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr v-if="list.length">
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="index">
          <td>{{index+1}}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="delInfo(item.id)">删除</button>
            <button @click="edit(item.id)" >编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
       list:[
        { 
          id:1,
          uname:'张三',
          age:19,
          gender:'男'
        },
        {
          id:2,
          uname:'龚彪',
          age:30,
          gender:'男'
        },
       ],
       uname:'',
       age:'',
       gender:'',
       flag:false,
       sta:''
    }
  },
  methods:{
    //删除功能
   delInfo(id){
       this.list= this.list.filter(item =>item.id !==id )
        },
    //添加功能
    addInfo(){
        if(!this.flag){
             if(this.uname &&this.age && this.gender){
             const obj = {
          id:this.list.length+1,
          uname:this.uname,
          age:this.age,
          gender:this.gender,
        }
          this.list =[...this.list,obj]
          this.uname=''
          this.age=''
          this.gender=''
       }else {
         alert('请输入用户信息')
       }
        } else{
           this.list.forEach(item =>{
             if(item.id===this.sta){
               item.uname=this.uname
               item.age=this.age
               item.gender=this.gender
               
             }
           }) 
           this.flag =false
        }
    },
    //修改
    edit(id){
       this.flag= true
       this.sta=id
     const editArr= this.list.filter(item=>item.id ===id)
     
      this.uname=editArr[0].uname
      this.age=editArr[0].age
      this.gender=editArr[0].gender
    }
  },
  
}
</script>